package com.jn.algorithm.day017.question47;

import java.util.*;

/**
 * @author 江南大学1033190417
 * @date 2022/5/8 14:39
 */
public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        Deque<Integer> path = new ArrayDeque<>();
        boolean[] used = new boolean[len];
        Arrays.sort(nums);
        dfs(0, len, path, used, res, nums);
        return res;
    }

    private void dfs(int depth, int len, Deque<Integer> path, boolean[] used, List<List<Integer>> res, int[] nums) {
        if (depth == len) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (used[i]) {//首先用过的直接跳过
                continue;
            }
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {//关键步骤：同一深度，如果和左侧的相同直接剪枝
                continue;
            }
            used[i] = true;
            path.addLast(nums[i]);
            dfs(depth + 1, len, path, used, res, nums);
            used[i] = false;
            path.removeLast();
        }
    }


    public static void main(String[] args) {
        int[] nums = new int[]{3, 3, 0, 3};
        Solution solution = new Solution();
        System.out.println(solution.permuteUnique(nums));
    }
}
